const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const Schema = mongoose.Schema;
let ObjectId = Schema.Types.ObjectId;
const saltRounds = 10;

// 创建userschema
const userSchema = new Schema({
  userId: {type: ObjectId},
  userName: {unique: true,type: String},
  grade: {type: String, default: 'D'},
  phoneNumber: {unique: true,type: String},
  password: String,
  createAt: {type: Date, default: Date.now},
  lastLoginAt: {type: Date, default: Date.now}
})

userSchema.pre('save',function (next) {
  bcrypt.genSalt(saltRounds, (err, salt) => {
    if(err) {
      return next(err);
    }
    bcrypt.hash(this.password, salt,(err, hash) => {
      if(err) {
        return next(err);
      }
      this.password = hash;
      next();
    });
});
})

// 发布模型
mongoose.model('User',userSchema);
